package com.hhd.pdf.context;

import com.alibaba.fastjson.JSONObject;
import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.GeneratorParameters;
import com.hhd.pdf.variable.VariableContext;
import com.hhd.pdf.variable.VariablePath;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.dom4j.Document;
import org.dom4j.Element;

@Builder
@Getter
@Setter
public class GeneratorContext {
    GeneratorParameters generatorParameters;
    com.itextpdf.text.Document document;
    Document xmlDocument;
    RuntimeData runtimeData;

    public GeneratorContext clone() {
        return GeneratorContext.builder()
                .generatorParameters(generatorParameters.clone())
                .document(document)
                .xmlDocument(xmlDocument)
                .runtimeData(runtimeData)
                .runtimeData(CommonUtils.isEmpty(runtimeData) ? null : runtimeData.clone())
                .build();
    }

    public void closeFiles() {
        try {
            document.close();
        } catch (Exception e) {
        }
    }

    public GeneratorContext runtime() {
        Element parsingElement = getRuntimeData().getParsingElement();
        GeneratorContext clone = this.clone();
        clone.getRuntimeData().setParsingElement(parsingElement);
        return clone;
    }

    public GeneratorContext runtime(Element parsingElement) {
        GeneratorContext clone = this.clone();
        clone.getRuntimeData().setParsingElement(parsingElement);
        clone.getRuntimeData().setVariableContext(getVariableContext());
        return clone;
    }

    public GeneratorContext rootRuntime(Element parsingElement) {
        GeneratorContext clone = this.clone();
        VariableContext context = VariableContext.builder()
                .basePath(VariablePath.root())
                .container(generatorParameters.getRenderData())
                .build();
        clone.setRuntimeData(new RuntimeData(parsingElement, context));
        return clone;
    }

    public JSONObject getRenderData() {
        return getGeneratorParameters().getRenderData();
    }

    public VariableContext getVariableContext() {
        return getRuntimeData().getVariableContext();
    }

    public Element getParsingElement() {
        return getRuntimeData().getParsingElement();
    }

    @AllArgsConstructor
    @Getter
    @Setter
    public static class RuntimeData {
        Element parsingElement;
        VariableContext variableContext;

        public RuntimeData clone() {
            return new RuntimeData(parsingElement, variableContext);
        }
    }
}
